package com.tengju.bff.interfaces.covercharge.util.validator;

import com.zoi7.component.core.exception.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import java.util.Iterator;
import java.util.Set;

/**
 * JSR303手工校验
 *
 * @author fwy
 */
public class ValidaUtil {

    /**
     * @param requestVO VO or DTO
     * @param errorMsg  错误信息
     * @return
     */
    private static boolean baseCheckInputVO(Object requestVO, ErrorMsg errorMsg) {
        if (null == requestVO) {
            errorMsg.setMessage("入参vo不能为空");
            return false;
        }
        Set<ConstraintViolation<Object>> validResult = Validation.buildDefaultValidatorFactory().getValidator()
                .validate(requestVO);
        if (null != validResult && validResult.size() > 0) {
            errorMsg.setMessage(validResult.iterator().next().getMessage());
            return false;
        }
        return true;
    }

    public static void baseReqParamCheck(Object requestVO) {
        ErrorMsg errorMsg = new ErrorMsg();
        //JSR303校验
        boolean checkResult = baseCheckInputVO(requestVO, errorMsg);
        if (!checkResult) {
            throw new ServiceException(errorMsg.getMessage());
        }
    }


    public static Boolean isReqParamCheck(Object requestVO,ErrorMsg errorMsg) {
        //JSR303校验
        return baseCheckInputVO(requestVO, errorMsg);
    }
}
